package controller;

import bean.Model;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
public class FileController {

//    @PostMapping("upload")
//    public void upload(HttpServletRequest request) {
//        Mono<MultiValueMap<String, Part> body = request.body(toMultipartData());
//        body.flatMap(map -> FilePart part = (FilePart) map.toSingleValueMap().get("file"));
//    }
    @PostMapping("/upload")
    public Mono<String> process(@RequestPart("file") Flux<FilePart> filePartFlux) {
        try {
            return filePartFlux.flatMap(it -> it.transferTo(Paths.get("tmp/" + UUID.randomUUID() + it.filename().substring(it.filename().indexOf(".")))))
                    .then(Mono.just("OK"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @PostMapping("/upload-model")
    public Mono<String> processModel(@ModelAttribute Model model) {
        model.getFiles().forEach(it -> it.transferTo(Paths.get("tmp/" + UUID.randomUUID() + it.filename().substring(it.filename().indexOf(".")))));
        return Mono.just("OK");
    }


//    @PostMapping("/upload-function")
//    public Mono<ServerResponse> upload(ServerRequest request) {
//        Mono<String> then = request.multipartData().map(it -> it.get("file"))
//                .flatMapMany(Flux::fromIterable)
//                .cast(FilePart.class)
//                .flatMap(it -> it.transferTo(Paths.get("tmp/" + UUID.randomUUID() + it.filename().substring(it.filename().indexOf(".")))))
//                .then(Mono.just("OK"));
//        return ServerResponse.ok().body(then, String.class);
//    }

}
